package com.zhiche.lisa.bms.service.contract.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.zhiche.lisa.bms.dao.mapper.contract.ContractFleetDtlMapper;
import com.zhiche.lisa.bms.dao.model.contract.Contract;
import com.zhiche.lisa.bms.dao.model.contract.ContractFleetDtl;
import com.zhiche.lisa.bms.service.contract.ContractFleetDtlService;
import com.zhiche.lisa.core.supports.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同车队明细表 服务实现类
 * </p>
 *
 * @author liuanshun
 * @since 2018-11-06
 */
@Service
@Slf4j
public class ContractFleetDtlServiceImpl extends ServiceImpl<ContractFleetDtlMapper, ContractFleetDtl> implements ContractFleetDtlService {
    private EntityWrapper<ContractFleetDtl> bindContractFleetDtlWrapper(Map<String, Object> condition) {
        EntityWrapper<ContractFleetDtl> contractFleetDtlEntityWrapper = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            for (Map.Entry<String, Object> item :
                    condition.entrySet()) {
                if (!StringUtils.isEmpty(item.getValue())) {
                    if ("headId".equals(item.getKey())) {
                        contractFleetDtlEntityWrapper.eq("head_id", item.getValue());
                    }

                    if ("fleetId".equals(item.getKey())) {
                        contractFleetDtlEntityWrapper.eq("fleet_id", item.getValue());
                    }

                    if ("inFleetId".equals(item.getKey())) {
                        contractFleetDtlEntityWrapper.in("fleet_id", JSONArray.parseArray(JSONObject.toJSONString(item.getValue())));
                    }

                }
            }
        }
        return contractFleetDtlEntityWrapper;
    }

    /**
     * 查询合同车队明细集合
     *
     * @return
     */
    @Override
    public List<ContractFleetDtl> selectContractFleetDtlList(Map<String, Object> param) {
        return this.selectList(bindContractFleetDtlWrapper(param));
    }

    /**
     * 根据合同信息寻找匹配详明
     *
     * @param contract
     * @return
     */
    @Override
    public List<ContractFleetDtl> selectContractFleetDtlByContract(Contract contract) {
        List<ContractFleetDtl> returnContractFleetDtl = new ArrayList<>();
        if (contract == null || contract.getId() == null) {
            throw new BaseException("合同不存在");
        }

        Map<String, Object> contractFleetEw = new HashMap<>();
        contractFleetEw.put("headId", contract.getId());
        contractFleetEw.put("inFleetId", contract.getFleetIdList());
        List<ContractFleetDtl> contractFleetDtls = this.selectContractFleetDtlList(contractFleetEw);

        if (!CollectionUtils.isEmpty(contractFleetDtls)) {
            contractFleetDtls.forEach(contractFleetDtl -> {
                if (ArrayUtils.contains(contract.getFleetIdList(), (contractFleetDtl.getFleetId()==null)?null:(contractFleetDtl.getFleetId().toString()))) {
                    returnContractFleetDtl.add(contractFleetDtl);
                }
            });
        }
        return returnContractFleetDtl;
    }

    /**
     * 查询合同车队明细分页信息
     *
     * @return
     */
    @Override
    public Page<ContractFleetDtl> selectContractFleetDtlPage(Page<ContractFleetDtl> contractFleetDtlPage) {
        return this.selectPage(contractFleetDtlPage.setCondition(new HashMap<>()),
                bindContractFleetDtlWrapper(contractFleetDtlPage.getCondition()));
    }

    /**
     * 根据合同id查询合同车队明细
     *
     * @return
     */
    @Override
    public List<ContractFleetDtl> selectContractFleetDtlsByHeaderId(Long headerId) {
        EntityWrapper<ContractFleetDtl> objectEntityWrapper = new EntityWrapper<>();
        objectEntityWrapper.eq("head_id", headerId);
        return this.selectList(objectEntityWrapper);
    }

    /**
     * 新增合同车队明细
     *
     * @param contractFleetDtls
     * @param headerId
     * @return
     */
    @Override
    public List<ContractFleetDtl> insertContractFleetDtls(List<ContractFleetDtl> contractFleetDtls, Long headerId) {
        try {
            if (CollectionUtils.isEmpty(contractFleetDtls)) {
                return null;
            }
            contractFleetDtls.forEach(contractFleetDtl -> contractFleetDtl.setHeadId(headerId));
            this.insertBatch(contractFleetDtls);
            return contractFleetDtls;
        } catch (BaseException e) {
            log.error("ContractFleetDtlServiceImpl.insertContractFleetDtls error: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("ContractFleetDtlServiceImpl.insertContractFleetDtls error: {}", e.getMessage());
            throw new BaseException("新增合同车队详明错误");
        }
    }

    /**
     * 编辑合同车队详明信息
     *
     * @param inContractFleetDtl
     * @param headerId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<ContractFleetDtl> editContractFleetDtls(List<ContractFleetDtl> inContractFleetDtl, Long headerId) {
        try {
            //验证数据，并获取原绑定数据
            List<ContractFleetDtl> returnContractFleetDtls = new ArrayList<>();
            if (headerId == null || CollectionUtils.isEmpty(inContractFleetDtl)) {
                return returnContractFleetDtls;
            }
            List<ContractFleetDtl> contractFleetDtls = this.selectContractFleetDtlsByHeaderId(headerId);
            if (!CollectionUtils.isEmpty(contractFleetDtls)) {
                /*
                 * 判断对应数据时新增还是编辑状态
                 */
                List<Long> oldIds = new ArrayList<>();
                contractFleetDtls.forEach(contractFleetDtl -> oldIds.add(contractFleetDtl.getId()));

                List<ContractFleetDtl> addContractFleetDtls = new ArrayList<>();
                List<ContractFleetDtl> updateIdsContractFleetDtls = new ArrayList<>();
                for (ContractFleetDtl contractFleetDtl :
                        inContractFleetDtl) {
                    if (contractFleetDtl.getId() != null) {
                        if (oldIds.contains(contractFleetDtl.getId())) {
                            updateIdsContractFleetDtls.add(contractFleetDtl);
                            oldIds.remove(contractFleetDtl.getId());
                            continue;
                        }
                    }
                    addContractFleetDtls.add(contractFleetDtl);
                }
                //回写数据库
                if (!CollectionUtils.isEmpty(addContractFleetDtls)) {
                    this.insertContractFleetDtls(addContractFleetDtls, headerId);
                }
                if (!CollectionUtils.isEmpty(updateIdsContractFleetDtls)) {
                    this.updateBatchById(updateIdsContractFleetDtls);
                }
                if (!CollectionUtils.isEmpty(oldIds)) {
                    this.deleteBatchIds(oldIds);
                }
            }
            return returnContractFleetDtls;
        } catch (BaseException e) {
            log.error("ContractFleetDtlServiceImpl.editContractFleetDtls error: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("ContractFleetDtlServiceImpl.editContractFleetDtls error: {}", e.getMessage());
            throw new BaseException("编辑合同车队详明异常");
        }
    }
}
